<template>
  <!--编辑Modal-->
  <a-modal title="操作" :width="800" v-model="visible" @ok="handleSubmit" @cancel="resetForm">
    <a-form :form="form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-form-item label="唯一识别码" v-show="form.getFieldValue('id') > 0">
        <a-input placeholder="唯一识别码" v-decorator="['id', { initialValue: 0 }]" disabled/>
      </a-form-item>
      <a-form-item label="资源名称">
        <a-input placeholder="资源名称" v-decorator="['title']"/>
      </a-form-item>
      <a-form-item label="路由地址">
        <a-input placeholder="路由地址" v-decorator="['path']"/>
      </a-form-item>
      <a-form-item label="组件名称">
        <a-input placeholder="组件名称" v-decorator="['name']"/>
      </a-form-item>
      <a-form-item label="组件图标">
        <a-input v-decorator="['icon']" disabled>
          <a-icon slot="addonBefore" :type="icon||''"/>
          <a-popover slot="addonAfter" v-model="iconVisible" title="选择图标" trigger="click">
            <div slot="content" style="width: 500px">
              <icon-selector v-model="icon" @change="handleIconChange"/>
            </div>
            <a-button type="primary">选择图标</a-button>
          </a-popover>
        </a-input>
      </a-form-item>
      <a-form-item label="排序">
        <a-input placeholder="排序" v-decorator="['sort']"/>
      </a-form-item>
      <a-form-item label="父级菜单">
        <a-tree-select
          showSearch
          tree-data-simple-mode
          v-decorator="['parentId']"
          :tree-default-expanded-keys="[0]"
          placeholder="请选择父级菜单"
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
          :tree-data="treeData"
          :filterTreeNode="filterTreeNode"
        />
      </a-form-item>
      <a-form-item label="状态">
        <a-select v-decorator="['status']">
          <a-select-option :value="0">正常</a-select-option>
          <a-select-option :value="1">禁用</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="赋予权限">
        <a-select style="width: 100%" mode="multiple" v-decorator="['actions']" :allowClear="true">
          <a-select-option v-for="(action, index) in permissionList" :key="index" :value="action.value">{{ action.label }}</a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
import { saveOrUpdateResource, loadResourceTree } from '@/api/resource'
import { loadPermissionList } from '@/constants/commonConstant'
import { pick, map } from 'lodash'
import { labelCol, wrapperCol } from '@/constants/FormConstant'
import icons from '@/components/IconSelector/icons'
import IconSelector from '@/components/IconSelector/IconSelector'
import { INIT_FIELD } from '@/views/permission/constant'

const pickFields = map(INIT_FIELD, (v, k) => k)
export default {
  name: 'CreateModal',
  components: {
    IconSelector
  },
  data() {
    return {
      icons,
      icon: 'user',
      labelCol,
      wrapperCol,
      visible: false,
      editVisible: false,
      iconVisible: false,
      // 向后端拉取可以用的操作列表
      permissionList: null,
      form: this.$form.createForm(this),
      treeData: []
    }
  },
  mounted() {
    // 防止表单未注册
    pickFields.forEach(v => this.form.getFieldDecorator(v))
    this.loadPermissionList()
  },
  methods: {
    loadPermissionList,
    add() {
      this.edit(INIT_FIELD)
    },
    edit(record) {
      this.onLoadData()
      const { form: { setFieldsValue } } = this
      this.$nextTick(() => {
        setTimeout(() => {
          setFieldsValue(pick(Object.assign({}, record), pickFields))
        })
      })
      this.icon = record.icon
      this.visible = true
      this.editVisible = true
    },
    handleSubmit() {
      const { form: { validateFields } } = this
      this.confirmLoading = true
      validateFields((errors, values) => {
        if (!errors) {
          saveOrUpdateResource(values).then(response => {
            if (response.success) {
              this.visible = false
              this.$emit('ok')
              this.$message.success(response.message)
            } else {
              this.$message.error(response.message)
            }
          }).catch(error => {
            this.$message.error(error.message)
          })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.visible = false
    },
    handleIconChange(icon) {
      this.icon = icon
      this.$nextTick(() => {
        this.form.setFieldsValue({ 'icon': icon })
      })
    },
    // 获取父级菜单下拉数据
    onLoadData() {
      loadResourceTree().then(response => {
        if (response.success) {
          this.treeData = [{ id: 0, pId: -1, title: '根节点', value: '0', leaf: false, children: [...response.result] }]
        } else {
          this.$message.error(response.message || '数据获取失败')
        }
      }).catch(error => {
        this.$message.error((error && error.message) || '数据获取失败')
      })
    },
    // 过滤节点内容
    filterTreeNode(inputValue, treeNode) {
      return treeNode.data.props.title.includes(inputValue) || treeNode.data.props.value.includes(inputValue)
    },
    // 重置表单
    resetForm() {
      this.form.resetFields()
    }
  }
}
</script>

<style lang="less">
  .ant-form-item-children {
    .ant-input-group-wrapper {
      .ant-input-wrapper {
        .ant-input {
          height: 34px !important;
        }

        .ant-input-group-addon:last-child {
          padding: 0;
        }
      }
    }
  }
</style>
